package com.leather.admin.controller;

import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Maps;
import com.leather.admin.entity.Role;
import com.leather.admin.service.RoleService;
import com.leather.common.result.CodeMsg;
import com.leather.common.result.Result;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin/role")
public class RoleController {

    @Autowired
    private RoleService roleService;


    @GetMapping("/index")
    public String index() {
        return "role/index";
    }


    @RequiresPermissions("admin:role:index")
    @ResponseBody
    @GetMapping("list")
    public Object getPermission() {
        Map<String, Object> map = Maps.newHashMap();
        List<Role> roles = roleService.list();
        map.put("total", roles.size());
        map.put("rows", roles);
        return map;
    }

    @RequiresPermissions("admin:role:create")
    @GetMapping("/create")
    public String create() {
        return "role/create";
    }

    @ResponseBody
    @RequiresPermissions("admin:role:create")
    @PostMapping("/create")
    public Object postCreate(Role role) {
        return roleService.addRole(role);
    }

    @RequiresPermissions("admin:role:update")
    @GetMapping("/update/{id}")
    public String update(@PathVariable("id") int id, Model model) {
        Role role = roleService.getById(id);
        model.addAttribute("role", role);
        return "role/update";
    }

    @ResponseBody
    @RequiresPermissions("admin:role:update")
    @PostMapping("/update")
    public Object postUpdate(Role role) {
        if (roleService.updateById(role)) {
            return Result.success("success");
        } else {
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }

    @RequiresPermissions("admin:role:setpermission")
    @RequestMapping(value = "/setpermission", method = RequestMethod.GET)
    public String permission() {
        return "role/permission";
    }

    @RequiresPermissions("admin:role:setpermission")
    @PostMapping("/setpermission/{id}")
    @ResponseBody
    public Object setPermission(@PathVariable("id") int id, HttpServletRequest request) {
        JSONArray datas = JSONArray.parseArray(request.getParameter("datas"));
        try {
            return roleService.setRolePermission(id, datas);
        } catch (Exception e) {
            return Result.exception(600000, e.getMessage());
        }
    }


    @RequiresPermissions("admin:role:setpermission")
    @PostMapping("/getrolepermission/{id}")
    @ResponseBody
    public Object role(@PathVariable("id") int id) {
        return roleService.getTreeByRoleId(id);
    }


}
